package cn.itcast.web.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import cn.itcast.util.HttpUtils;
import cn.itcast.util.WxUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
public class WxLoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @RequestMapping(value = "/weixinlogin" ,name = "用户微信登录")
    public String weixinloin(String code){

        return "redirect:/wxlogin.do?code=" + code;
    }


    @RequestMapping(value = "/wxlogin.do" ,name = "扫码登录")
    public String login(String code){

        Map<String, String> authorization = WxUtil.getAuthorization(code);

        if (authorization.size() > 0){
            String access_token = authorization.get("access_token");
            String openid = authorization.get("openid");

            // 查询微信登录用户是否存在
            User userByWxOpenId = userService.findByWxOpenId(openid);
            if (userByWxOpenId == null) {
                // 用户不存在, 则绑定
                request.setAttribute("wxOpenId", openid);
                request.setAttribute("wxSuccess", 0);
                session.setAttribute("accessToken", access_token);
                //return "forward:/login/wxBind";
            } else {
                // 用户存在, 登录
                //jkalg
                String email = userByWxOpenId.getEmail();
                String password4DBWithWx = userByWxOpenId.getPassword();
                if (!loginWithShiro(email, password4DBWithWx)) {
                    // 登录失败
                    return "forward:/login.jsp";
                } else {
                    // 登录成功
                    return "home/main";
                }
            }
        }

        // 转发到绑定页面
        return "forward:/login.jsp";
    }

    private boolean loginWithShiro(String email, String md5Pwd) {

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(email, md5Pwd);

        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {

            request.setAttribute("error", "账户邮箱或密码输入有误! ");
            return false;
        }

        User user = (User) subject.getPrincipal();

        // 将登录信息放入HttpSession
        session.setAttribute("loginUser", user);

        // 获取登录信息菜单, 并放入HttpSession
        List<Module> modules = moduleService.findModuleListByUser(user);
        session.setAttribute("modules", modules);
        return true;
    }


    @RequestMapping(value = "/wxBind.do", name = "用户微信登录绑定信息")
    public String wxBind(String email, String password, String openId) {
        // 绑定邮箱
        User loginUser = userService.findByEmail(email);


        if (loginUser == null){
            // 用户不存在
            // 转发到绑定页面
            request.setAttribute("error", "绑定邮箱不存在, 请联系管理员!");
            return "forward:/wxlogin.do";
        }



        String md5Pwd = new Md5Hash(password, email,2).toString();
        UsernamePasswordToken token = new UsernamePasswordToken(email, md5Pwd);

        //2.获取主体对象（工具类）
        Subject subject = SecurityUtils.getSubject();

        // 3.调用subject的登录方法
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            // 密码不正确
            request.setAttribute("error", "密码不正确");
            return "forward:/wxlogin.do";
        }
        Object accessToken = session.getAttribute("accessToken");
        Map<String, String> userInfo = WxUtil.getUserInfo(String.valueOf(accessToken), openId);
        String userName = userInfo.get("nickname");
        String headimgurl = userInfo.get("headimgurl");

        loginUser.setHeadUrl(headimgurl);
        loginUser.setUserName(userName);
        loginUser.setOpenid(openId);
        userService.update(loginUser);

        // 4.从shiro中获取登录成功的user对象
        loginUser = (User) subject.getPrincipal();

        // 5.存储到session域
        session.setAttribute("loginUser", loginUser);

        // shiro认证代码 end

        // 查询动态菜单
        List<Module> modules = moduleService.findModuleListByUser(loginUser);
        session.setAttribute("modules", modules);
        return "home/main";

    }
}
